package com.mzj.saas.mservice.application.service;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.util.StringUtils;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.application.entity.ApprovalProcessUser;
import com.mzj.saas.mservice.application.entity.HouseAuditSet;
import com.mzj.saas.mservice.application.entity.HousePutRecordsSet;
import com.mzj.saas.mservice.application.repository.ApprovalProcessNodeRepository;
import com.mzj.saas.mservice.application.repository.ApprovalProcessUserRepository;
import com.mzj.saas.mservice.application.repository.HouseAuditSetRepository;
import com.mzj.saas.mservice.application.repository.HousePutRecordsSetRepository;
import com.mzj.saas.mservice.application.vo.*;
import com.mzj.saas.mservice.area.entity.Area;
import com.mzj.saas.mservice.area.repository.AreaRepository;
import com.mzj.saas.mservice.eligible.entity.ApplyAudit;
import com.mzj.saas.mservice.eligible.entity.DepartmentEnterpriseTagRef;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.ApplyAuditRepository;
import com.mzj.saas.mservice.eligible.repository.DepartmentEnterpriseTagRefRepository;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class AppRoverSetService {
    private static final Logger LOG = LoggerFactory.getLogger(AppRoverSetService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private HouseAuditSetRepository houseAuditSetRepository;
    @Autowired
    private HousePutRecordsSetRepository housePutRecordsSetRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ApprovalProcessNodeRepository approvalProcessNodeRepository;
    @Autowired
    private ApprovalProcessUserRepository approvalProcessUserRepository;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private ApplyAuditRepository applyAuditRepository;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;

    /*
     *资格审批人列表
     */

    /**
     * 资格审批人列表,实现了资格审批人列表的显示
     *
     * @param accessToken 权限鉴定
     * @param pageNumber  当前页
     * @param pageSize    页数
     * @return
     */
    public ResultBean<Object> qualificationExaminerListShow(String accessToken, Integer pageNumber, Integer pageSize) {
        //记录日志
        LOG.info("AppRoverSetService qualificationExaminerListShow accessToken={}", accessToken);
        //创建返回值，设置返回值
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        resultBean.setResultData(Collections.emptyList());
        //获取用户登录权限
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        ApiData<Map<String, Object>> apiData = new ApiData<>();
        List<Map<String, Object>> result = new ArrayList<>();
        try {
            //用户权限的鉴定
            if (tokenRedisVo == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return resultBean;
            }
            //根据用户ID查询出用户层级权限
            DepartmentHierarchy company = departmentHierarchyRepository.findByOrgId(tokenRedisVo.getEnterpriseId());
            if (company == null) {
                return ResultBean.failedResultWithMsg("企业层级信息有误或不存在");
            }

            String sql = "SELECT  DISTINCT org_id FROM ( SELECT t1.id,t1.`org_id`,t1.`area_id`,t1.`tag_id`,IF(FIND_IN_SET(parent_id, @pids) > 0,@pids := CONCAT(@pids, ',', id),0) AS ischild FROM (SELECT id, parent_id, t.`org_id`,t.`area_id`,t.`tag_id` FROM `saas_department_hierarchy` t ORDER BY parent_id,id ) t1,(SELECT @pids :=? ) t2 ) t3  WHERE  ischild != 0  ";
            List<Long> orgIds = new ArrayList<>();
            StringBuffer orgIdWhere = new StringBuffer();
            //查询存储机构ID
            orgIds.addAll(jdbcTemplate.queryForList(sql, new Object[]{company.getId()}, Long.class));
            //遍历机构ID
            for (Long orgId : orgIds) {
                orgIdWhere.append(orgId).append(",");
            }
            //获取企业ID
            orgIdWhere.append(tokenRedisVo.getEnterpriseId());
            StringBuffer sbSql = new StringBuffer("SELECT * FROM `saas_approval_process_user` WHERE 1=1  ");
            if (!StringUtils.isBlank(orgIdWhere.toString())) {
                sbSql.append("  AND  `org_id`  IN  (" + orgIdWhere.toString() + ")  ");
            }
            String count = "SELECT COUNT(0) FROM  (" + sbSql + ")  c";
            String offsets = "  LIMIT ? OFFSET ? ";
            // 查询总记录数
            Long total = jdbcTemplate.queryForObject(count, Long.class);
            if (total == 0) {
                resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
                resultBean.setResultData(null);
                return resultBean;
            }
            // 查询分页数据
            List<Object> args = new ArrayList<>();
            sbSql.append(offsets);
            //设置当前页
            args.add(pageSize);
            //设置页数
            args.add(pageNumber * pageSize);
            //后期申批人数据
            List<ApprovalProcessUserVO> ApprovalProcessUserList = jdbcTemplate.query(sbSql.toString(), new BeanPropertyRowMapper<>(ApprovalProcessUserVO.class), args.toArray());
            //遍历设置审批人数据
            for (ApprovalProcessUserVO approvalProcessUserVO : ApprovalProcessUserList) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", approvalProcessUserVO.getId());
                map.put("typeName", "公租房资格审批人");
                map.put("preSentOrgId", tokenRedisVo.getEnterpriseId());

                map.put("status", approvalProcessUserVO.getStatus());

                User user = userRepository.findById(approvalProcessUserVO.getAuditorUserId());
                map.put("auditorUserId", user == null ? null : user.getId());
                map.put("auditorUserName", user == null ? "暂未设置" : user.getName());

                Area area = areaRepository.findById(approvalProcessUserVO.getAreaId()).get();
                map.put("areaId", approvalProcessUserVO.getAreaId());
                map.put("areaName", area.getName());

                DepartmentHierarchy departmentHierarchy = departmentHierarchyRepository.findByOrgId(approvalProcessUserVO.getOrgId());
                map.put("orgName", departmentHierarchy.getName());

                if (tokenRedisVo.getEnterpriseId().equals(approvalProcessUserVO.getOrgId())) {
                    //审批人设置权限
                    map.put("operatePoint", 1);
                } else {
                    map.put("operatePoint", 0);
                }

                map.put("lastUpdateTime", approvalProcessUserVO.getLastUpdateTime());
                result.add(map);
            }
            //存储数据并返回给前端页面
            apiData.setData(result);
            apiData.setTotal(total);
            resultBean.setResultData(apiData);
        } catch (Exception e) {
            //记录报错日志
            LOG.error(e.getMessage(), e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(e.getMessage());
        }
        return resultBean;
    }

    /*
     *设置公租房资格审批人
     */
    /*public ResultBean<Object> appRoverSetQualificationExaminer(String accessToken, ApprovalProcessUserVO approvalProcessUserVO) {
        LOG.info("AppRoverSetService appRoverSetQualificationExaminer accessToken={},approvalProcessUserVO={}", accessToken, approvalProcessUserVO);
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return resultBean;
            }

            if (approvalProcessUserVO.getId() == null) {
                return ResultBean.failedResultWithMsg("审批流程审批人设置表id不存在");
            }

            User user = userRepository.findById(approvalProcessUserVO.getAuditorUserId());
            if (user == null) {
                return ResultBean.failedResultWithMsg("审批人信息有误或不存在");
            }

            Optional<ApprovalProcessUser> entity = approvalProcessUserRepository.findById(approvalProcessUserVO.getId());
            ApprovalProcessUser approvalProcessUser = entity.get();
            String oldAuditorUserId = approvalProcessUser.getAuditorUserId();

            approvalProcessUser.setOperationId(tokenRedisVo.getId());
            approvalProcessUser.setAuditorUserId(approvalProcessUserVO.getAuditorUserId());
            approvalProcessUser.setLastUpdateTime(new Date());

            approvalProcessUserRepository.save(approvalProcessUser);

            //同步更新下saas_house_apply_audit(公租房审批明细表)
            //1、查询出所有 current_audit_id = 旧审批人的数据
            List<ApplyAudit> applyAuditList = applyAuditRepository.findByCurrentAuditId(oldAuditorUserId);

            if (!applyAuditList.isEmpty()) {
                for (ApplyAudit applyAudit : applyAuditList) {
                    if (applyAudit.getAuditStatus() == 0 || applyAudit.getAuditStatus() == 1) {
                        applyAudit.setCurrentAuditId(approvalProcessUserVO.getAuditorUserId());
                    }
                    applyAuditRepository.save(applyAudit);
                }
            }

        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(e.getMessage());
        }
        return resultBean;
    }*/
    /**
     * 审批人设置-设置 公租房资格审批人
     * @param accessToken 权限鉴定
     * @param approvalProcessUserVO
     * @return
     */
    public ResultBean<Object> appRoverSetQualificationExaminer(String accessToken, ApprovalProcessUserVO vo) {
        LOG.info("AppRoverSetService appRoverSetQualificationExaminer accessToken={},vo={}", accessToken, vo);
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);

        try {
            if (tokenRedisVo == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return resultBean;
            }

            if (vo.getId() == null) {
                return ResultBean.failedResultWithMsg("id不存在");
            }

            if (StringUtils.isBlank(vo.getAuditorUserId())) {
                return ResultBean.failedResultWithMsg("审批人id不存在");
            }

            User user = userRepository.findById(vo.getAuditorUserId());
            if (user == null) {
                return ResultBean.failedResultWithMsg("审批人信息不存在");
            }

            Optional<ApprovalProcessUser> entity = approvalProcessUserRepository.findById(vo.getId());
            if (!entity.isPresent()) {
                return ResultBean.failedResultWithMsg("审批人设置信息不存在");
            }
            ApprovalProcessUser approvalProcessUser = entity.get();

            approvalProcessUser.setOperationId(tokenRedisVo.getId());
            approvalProcessUser.setAuditorUserId(vo.getAuditorUserId());
            approvalProcessUser.setLastUpdateTime(new Date());
            approvalProcessUserRepository.save(approvalProcessUser);

            //更新公租房审批流程审批人
            Long areaId = approvalProcessUser.getAreaId();
            List<ApplyAudit> applyAuditList = applyAuditRepository.findByOrgAreaId(areaId);
            for (ApplyAudit applyAudit : applyAuditList) {
                if (applyAudit.getAuditStatus() == 0 || applyAudit.getAuditStatus() == 1) {
                    applyAudit.setCurrentAuditId(vo.getAuditorUserId());
                }
                applyAuditRepository.save(applyAudit);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(e.getMessage());
        }
        return resultBean;
    }

    /**
     * 信息备案确定人列表,实现了信息备案确定人列表的显示
     *
     * @param accessToken 权限鉴定
     * @param pageNumber  当前页
     * @param pageSize    页数
     * @return
     */
    public ResultBean<Object> informationDeterminerListShow(String accessToken, Integer pageNumber, Integer pageSize) {
        //记录日志
        LOG.info("AppRoverSetService informationDeterminerListShow accessToken={}", accessToken);
        //默认返回成功
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        resultBean.setResultData(Collections.emptyList());
        //获取用户登录权限
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        ApiData<Map<String, Object>> apiData = new ApiData<>();
        List<Map<String, Object>> result = new ArrayList<>();
        try {
            //用户权限的鉴定
            if (tokenRedisVo == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return resultBean;
            }
            //根据企业ID查询出用户层级权限
            DepartmentHierarchy company = departmentHierarchyRepository.findByOrgId(tokenRedisVo.getEnterpriseId());
            if (company == null) {
                return ResultBean.failedResultWithMsg("企业层级信息有误或不存在");
            }
            //查找当前层级架构下所有为社区的orgId
            String sql = "SELECT  DISTINCT org_id FROM ( SELECT t1.id,t1.`org_id`,t1.`area_id`,t1.`tag_id`,IF(FIND_IN_SET(parent_id, @pids) > 0,@pids := CONCAT(@pids, ',', id),0) AS ischild FROM (SELECT id, parent_id, t.`org_id`,t.`area_id`,t.`tag_id` FROM `saas_department_hierarchy` t ORDER BY parent_id,id ) t1,(SELECT @pids :=? ) t2 ) t3  WHERE  ischild != 0  AND tag_id=5  ";
            List<Long> orgIds = new ArrayList<>();
            StringBuffer orgIdWhere = new StringBuffer();
            orgIds.addAll(jdbcTemplate.queryForList(sql, new Object[]{company.getId()}, Long.class));
            for (Long orgId : orgIds) {
                orgIdWhere.append(orgId).append(",");
            }
            String orgIdString = null;
            if (StringUtils.isNotBlank(orgIdWhere)) {
                orgIdString = orgIdWhere.toString().substring(0, orgIdWhere.toString().lastIndexOf(","));
            }
            if (company.getTagId() == 5) {
                orgIdString = orgIdString + "," + tokenRedisVo.getEnterpriseId();
            }
            StringBuffer sbSql = new StringBuffer("SELECT `id`,`org_id`,`parent_id`,`tag_id`,`name`,`area_id`,`auditor_user_id`,`code`,`sortby`,`status`,`last_update_time` FROM `saas_department_hierarchy`   WHERE 1=1  ");
            sbSql.append("  AND  `org_id`  IN  (" + orgIdString + ")  ");
            String count = "SELECT COUNT(0) FROM  (" + sbSql + ")  c";
            String offsets = "  LIMIT ? OFFSET ? ";
            // 查询总记录数
            Long total = jdbcTemplate.queryForObject(count, Long.class);
            if (total == 0) {
                resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
                resultBean.setResultData(null);
                return resultBean;
            }
            // 查询分页数据
            List<Object> args = new ArrayList<>();
            sbSql.append(offsets);
            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<DepartmentHierarchyVO> departmentHierarchyVOList = jdbcTemplate.query(sbSql.toString(), new BeanPropertyRowMapper<>(DepartmentHierarchyVO.class), args.toArray());
            for (DepartmentHierarchyVO departmentHierarchyVO : departmentHierarchyVOList) {
                Map<String, Object> map = new HashMap<>();
                map.put("typeName", "公租房信息备案确定人");
                map.put("status", 0);
                List<FlowShowVO> flowShowVOList = new ArrayList<>();
                DepartmentHierarchy existDepartmentHierarchy = departmentHierarchyRepository.findByOrgId(departmentHierarchyVO.getOrgId());
                HousePutRecordsSet housePutRecordsSet = housePutRecordsSetRepository.findByOrgId(departmentHierarchyVO.getOrgId());
                FlowShowVO flowShowVO = new FlowShowVO();
                flowShowVO.setOrgId(departmentHierarchyVO.getOrgId());
                flowShowVO.setName(existDepartmentHierarchy.getName());
                if (housePutRecordsSet != null) {
                    User user = userRepository.findById(housePutRecordsSet.getConfirmorId());
                    flowShowVO.setAuditorUserId(user == null ? null : user.getId());
                    flowShowVO.setAuditorUserName(user == null ? "暂未设置" : user.getName());
                    map.put("id", housePutRecordsSet.getId());
                    map.put("status", housePutRecordsSet.getStatus());
                    map.put("lastUpdateTime", housePutRecordsSet.getCreateTime());
                } else {
                    map.put("id", null);
                    flowShowVO.setAuditorUserId(null);
                    flowShowVO.setAuditorUserName("暂未设置");
                }
                flowShowVOList.add(flowShowVO);
                map.put("flow", flowShowVOList);
                map.put("lastUpdateTime", company.getLastUpdateTime());
                result.add(map);
            }
            apiData.setData(result);
            apiData.setTotal(total);
            resultBean.setResultData(apiData);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(e.getMessage());
        }
        return resultBean;
    }

    /**
     * 审批人设置-设置信息备案确定人
     * @param accessToken 权限鉴定
     * @param userId 确认人userId
     * @param orgId 社区节点orgId
     * @return
     */
    public ResultBean<Object> appRoverSetConfirmPeople(String accessToken, String userId, Long orgId) {
        LOG.info("AppRoverSetService appRoverSetConfirmPeople accessToken={},userId={},orgId={}", accessToken, userId, orgId);
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        resultBean.setResultData(Collections.emptyList());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return resultBean;
            }
            DepartmentHierarchy departmentHierarchy = departmentHierarchyRepository.findByOrgId(orgId);
            if (departmentHierarchy == null) {
                return ResultBean.failedResultWithMsg("企业层级信息有误或不存在");
            }
            HousePutRecordsSetVO housePutRecordsSetVO = new HousePutRecordsSetVO();
            housePutRecordsSetVO.setOrgId(departmentHierarchy.getOrgId());
            housePutRecordsSetVO.setAreaId(departmentHierarchy.getAreaId());
            housePutRecordsSetVO.setConfirmorId(userId);
            housePutRecordsSetVO.setOperationId(tokenRedisVo.getId());
            housePutRecordsSetVO.setStatus(1);
            housePutRecordsSetVO.setCreateTime(new Date());
            HousePutRecordsSet existHousePutRecordsSet = housePutRecordsSetRepository.findByOrgId(departmentHierarchy.getOrgId());
            if (existHousePutRecordsSet != null) {
                housePutRecordsSetVO.setId(existHousePutRecordsSet.getId());
                housePutRecordsSetVO.setStatus(existHousePutRecordsSet.getStatus());
            }
            HousePutRecordsSet housePutRecordsSet = new HousePutRecordsSet();
            BeanUtils.copyProperties(housePutRecordsSetVO, housePutRecordsSet);
            housePutRecordsSetRepository.save(housePutRecordsSet);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(e.getMessage());
        }
        return resultBean;
    }

    /**
     * 公租房绑定审批人列表,实现了公租房绑定审批人列表的显示
     * @param accessToken 权限鉴定
     * @param pageNumber 当前页
     * @param pageSize 页数
     * @return
     */
    public ResultBean<Object> bindingApproveListShow(String accessToken, Integer pageNumber, Integer pageSize) {
        LOG.info("AppRoverSetService bindingApproveListShow accessToken={},pageNumber={},pageSize={}", accessToken, pageNumber, pageSize);
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        resultBean.setResultData(Collections.emptyList());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        ApiData<Map<String, Object>> apiData = new ApiData<>();
        List<Map<String, Object>> result = new ArrayList<>();
        try {
            if (tokenRedisVo == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return resultBean;
            }
            DepartmentHierarchy company = departmentHierarchyRepository.findByOrgId(tokenRedisVo.getEnterpriseId());
            if (company == null) {
                return ResultBean.failedResultWithMsg("企业层级信息有误或不存在");
            }
            //查找当前层级架构下所有的orgId
            String sql = "SELECT  DISTINCT org_id FROM ( SELECT t1.id,t1.`org_id`,t1.`area_id`,t1.`tag_id`,IF(FIND_IN_SET(parent_id, @pids) > 0,@pids := CONCAT(@pids, ',', id),0) AS ischild FROM (SELECT id, parent_id, t.`org_id`,t.`area_id`,t.`tag_id` FROM `saas_department_hierarchy` t ORDER BY parent_id,id ) t1,(SELECT @pids :=? ) t2 ) t3  WHERE  ischild != 0    ";
            List<Long> orgIds = new ArrayList<>();
            StringBuffer orgIdWhere = new StringBuffer();
            orgIds.addAll(jdbcTemplate.queryForList(sql, new Object[]{company.getId()}, Long.class));
            orgIds.add(tokenRedisVo.getEnterpriseId());

            //过滤出住建局 : 5
            List<Long> orgIds5 = new ArrayList<>();
            for (Long orgId : orgIds) {
                DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgId(orgId);
                List<Long> tagIdList = departmentEnterpriseTagRefRepository.findByDepRefId(hierarchy.getId()).stream().map(DepartmentEnterpriseTagRef::getTagId).collect(Collectors.toList());
                if (tagIdList.contains(5L)) {
                    orgIds5.add(orgId);
                }

            }

            for (Long orgId : orgIds5) {
                orgIdWhere.append(orgId).append(",");
            }
            String orgIdString = null;
            if (StringUtils.isNotBlank(orgIdWhere)) {
                orgIdString = orgIdWhere.toString().substring(0, orgIdWhere.toString().lastIndexOf(","));
            }

            StringBuffer sbSql = new StringBuffer("SELECT `id`,`org_id`,`parent_id`,`tag_id`,`name`,`area_id`,`auditor_user_id`,`code`,`sortby`,`status`,`last_update_time` FROM `saas_department_hierarchy`   WHERE 1=1  ");
            sbSql.append("  AND  `org_id`  IN  (" + orgIdString + ")  ");
            String count = "SELECT COUNT(0) FROM  (" + sbSql + ")  c";
            String offsets = "  LIMIT ? OFFSET ? ";
            // 查询总记录数
            Long total = jdbcTemplate.queryForObject(count, Long.class);
            if (total == 0) {
                resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
                resultBean.setResultData(null);
                return resultBean;
            }
            // 查询分页数据
            List<Object> args = new ArrayList<>();
            sbSql.append(offsets);
            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<DepartmentHierarchyVO> departmentHierarchyVOList = jdbcTemplate.query(sbSql.toString(), new BeanPropertyRowMapper<>(DepartmentHierarchyVO.class), args.toArray());
            for (DepartmentHierarchyVO departmentHierarchyVO : departmentHierarchyVOList) {
                Map<String, Object> map = new HashMap<>();
                map.put("typeName", " 公租房绑定审批人");
                map.put("status", 0);
                List<FlowShowVO> flowShowVOList = new ArrayList<>();
                DepartmentHierarchy existDepartmentHierarchy = departmentHierarchyRepository.findByOrgId(departmentHierarchyVO.getOrgId());
                HouseAuditSet houseAuditSet = houseAuditSetRepository.findByOrgId(departmentHierarchyVO.getOrgId());
                FlowShowVO flowShowVO = new FlowShowVO();
                flowShowVO.setOrgId(departmentHierarchyVO.getOrgId());
                flowShowVO.setName(existDepartmentHierarchy.getName());
                if (houseAuditSet != null) {
                    User user = userRepository.findById(houseAuditSet.getAuditId());
                    flowShowVO.setAuditorUserId(user == null ? null : user.getId());
                    flowShowVO.setAuditorUserName(user == null ? "暂未设置" : user.getName());
                    map.put("id", houseAuditSet.getId());
                    map.put("status", houseAuditSet.getStatus());
                    map.put("lastUpdateTime", houseAuditSet.getCreateTime());
                } else {
                    map.put("id", null);
                    flowShowVO.setAuditorUserId(null);
                    flowShowVO.setAuditorUserName("暂未设置");
                }
                flowShowVOList.add(flowShowVO);
                map.put("flow", flowShowVOList);
                map.put("lastUpdateTime", company.getLastUpdateTime());
                result.add(map);
            }
            apiData.setData(result);
            apiData.setTotal(total);
            resultBean.setResultData(apiData);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(e.getMessage());
        }
        return resultBean;
    }

    /**
     * 审批人设置-设置公租房绑定审批人
     * @param accessToken 权限鉴定
     * @param userId 审批人userId
     * @param orgId 当前社区节点OrgId
     * @return
     */
    public ResultBean<Object> appRoverSetHouseBindingAuditingPeople(String accessToken, String userId, Long orgId) {
        LOG.info("AppRoverSetService appRoverSetHouseBindingAuditingPeople accessToken={},userId={},orgId={}", accessToken, userId, orgId);
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return resultBean;
            }
            DepartmentHierarchy departmentHierarchy = departmentHierarchyRepository.findByOrgId(orgId);
            if (departmentHierarchy == null) {
                return ResultBean.failedResultWithMsg("企业层级信息有误或不存在");
            }
            HouseAuditSetVO houseAuditSetVO = new HouseAuditSetVO();
            houseAuditSetVO.setAuditId(userId);
            houseAuditSetVO.setOperationId(tokenRedisVo.getId());
            houseAuditSetVO.setOrgId(departmentHierarchy.getOrgId());
            houseAuditSetVO.setAreaId(departmentHierarchy.getAreaId());
            houseAuditSetVO.setStatus(1);
            houseAuditSetVO.setCreateTime(new Date());
            HouseAuditSet existHouseAuditSet = houseAuditSetRepository.findByOrgId(departmentHierarchy.getOrgId());
            if (existHouseAuditSet != null) {
                houseAuditSetVO.setId(existHouseAuditSet.getId());
                houseAuditSetVO.setStatus(existHouseAuditSet.getStatus());
            }
            HouseAuditSet houseAuditSet = new HouseAuditSet();
            BeanUtils.copyProperties(houseAuditSetVO, houseAuditSet);
            houseAuditSetRepository.save(houseAuditSet);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(e.getMessage());
        }
        return resultBean;
    }


    /*
     *资格审批人/确定人/绑定审批人状态修改
     */
    public ResultBean<Object> appRoverStatusSet(String accessToken, UpdateAppRoverStatusVO updateAppRoverStatusVO) {
        LOG.info("AppRoverSetService appRoverStatusSet accessToken={},updateAppRoverStatusVO={}", accessToken, JSON.toJSONString(updateAppRoverStatusVO));
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return resultBean;
            }
            if (updateAppRoverStatusVO == null || updateAppRoverStatusVO != null && updateAppRoverStatusVO.getType() == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return resultBean;
            }
            switch (updateAppRoverStatusVO.getType()) {
                case 1:
                    if (updateAppRoverStatusVO.getId() == null) {
                        return ResultBean.failedResultWithMsg("修改id为空");
                    }
                    Optional<ApprovalProcessUser> existApprovalProcessUser = approvalProcessUserRepository.findById(updateAppRoverStatusVO.getId());
                    if (existApprovalProcessUser == null) {
                        return ResultBean.failedResultWithMsg("审批人设置记录不存在或是已删除");
                    }
                    ApprovalProcessUser approvalProcessUser = existApprovalProcessUser.get();
                    Long areaId = approvalProcessUser.getAreaId();
                    if (updateAppRoverStatusVO.getStatus().equals(1)) {  //启用时才验证   【审批人状态：0停用 1启用】
                        ApprovalProcessUser apu = approvalProcessUserRepository.findByAreaIdAndStatus(areaId, 1);
                        if (apu != null) {
                            return ResultBean.failedResultWithMsg("同一区域只能开启一个审批人");
                        }
                    }
                    approvalProcessUser.setStatus(updateAppRoverStatusVO.getStatus());
                    approvalProcessUser.setLastUpdateTime(new Date());
                    approvalProcessUserRepository.save(approvalProcessUser);
                    break;
                case 2:
                    if (updateAppRoverStatusVO.getId() == null) {
                        return ResultBean.failedResultWithMsg("当前还未绑定确认人信息或修改id为空");
                    }
                    HousePutRecordsSet housePutRecordsSet = housePutRecordsSetRepository.findById(updateAppRoverStatusVO.getId()).get();
                    if (housePutRecordsSet != null) {
                        housePutRecordsSet.setStatus(updateAppRoverStatusVO.getStatus());
                        housePutRecordsSet.setOperationId(tokenRedisVo.getId());
                        housePutRecordsSet.setCreateTime(new Date());
                        housePutRecordsSetRepository.save(housePutRecordsSet);
                    }
                    break;
                case 3:
                    if (updateAppRoverStatusVO.getId() == null) {
                        return ResultBean.failedResultWithMsg("公租房还未绑定审批人信息或修改id为空");
                    }
                    HouseAuditSet houseAuditSet = houseAuditSetRepository.findById(updateAppRoverStatusVO.getId()).get();
                    if (houseAuditSet != null) {
                        houseAuditSet.setStatus(updateAppRoverStatusVO.getStatus());
                        houseAuditSet.setOperationId(tokenRedisVo.getId());
                        houseAuditSet.setCreateTime(new Date());
                        houseAuditSetRepository.save(houseAuditSet);
                    }
                    break;
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(e.getMessage());
        }
        return resultBean;
    }
}


